import axios from 'axios'
import store from '@/store'
const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})

request.interceptors.request.use((config) => {
  // 注入token
  // store.getters.token => 请求头里面
  const token = store.getters.token // 获取vuex里面的token数据
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`
  }
  return config
}, (error) => {
  // 失败执行promise
  return Promise.reject(error)
})
// 响应拦截器
request.interceptors.response.use((res) => {
  const { code } = res.data // 默认json格式
  if (code === 200) {
    return res.data
  } else {
    return Promise.reject(new Error('Error'))
  }
}, async (error) => {
  // error.message

  return Promise.reject(error)
})

export default request
